#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //初始化树的基本信息
    ui->treeWidget->setHeaderLabel("动物");
    //设置顶层节点
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0,"猫");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item1->setText(0,"狗");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item1->setText(0,"鸡");
    ui->treeWidget->addTopLevelItem(item3);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addTop_clicked()
{
    //1.获取到输入框中的内容
    const QString& text = ui->lineEdit->text();
    if(text.isEmpty()) return;
    //2.添加到顶层元素中
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0,text);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_addCurrent_clicked()
{
    //1.获取到输入框中的内容
    const QString& text = ui->lineEdit->text();
    if(text.isEmpty()) return;
    //2.获取到当前节点
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if(currentItem == nullptr) return;
    //3.通过当前节点来添加当前的子节点
    QTreeWidgetItem* childItem = new QTreeWidgetItem();
    childItem->setText(0,text);
    currentItem->addChild(childItem);
    //扩展父节点
    currentItem->setExpanded(true);
}

void Widget::on_pushButton_delCurrent_clicked()
{
    //获取到当前节点
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if(currentItem == nullptr) return;
    //删除当前节点
    //获取到其父节点
    QTreeWidgetItem* parent = currentItem->parent();
    if(parent == nullptr)
    {
        //当前节点为顶点节点
        int index = ui->treeWidget->indexOfTopLevelItem(currentItem);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        parent->removeChild(currentItem);
    }
}
